package com.frog.lock.starter.lock;

import com.frog.lock.starter.model.LockInfo;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;

import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 读锁
 */
public class ReadLock implements Lock {

    private RReadWriteLock rLock;

    private String id;

    private final LockInfo lockInfo;

    private RedissonClient redissonClient;

    public ReadLock(RedissonClient redissonClient, LockInfo info) {
        this.redissonClient = redissonClient;
        this.lockInfo = info;
        this.rLock = redissonClient.getReadWriteLock(info.getName());
        if (this.id == null || "".equals(this.id)) {
            this.id = UUID.randomUUID().toString();
        }
    }

    @Override
    public String getLockId() {
        if (this.id == null || "".equals(this.id)) {
            this.id = UUID.randomUUID().toString();
        }
        return id;
    }

    @Override
    public boolean acquire() {
        try {
            if (rLock == null) {
                rLock = redissonClient.getReadWriteLock(lockInfo.getName());
            }
            return rLock.readLock().tryLock(lockInfo.getWaitTime(), lockInfo.getLeaseTime(), TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    @Override
    public boolean release() {
        try {
            rLock.readLock().unlock();
            return true;
        } catch (Exception e) {
            return false;
        }
    }


}
